<template>
	<view class="container">
		<uni-section title="克隆步骤" type="line" padding>
			<uni-steps :options="list1" :active="active"/>
		</uni-section>
		
		<!-- active:1 start -->
		<view class="content" v-if="active == 0">
			<view class="item">
				<view class="left">
					自定义声音的ID:
				</view>
				<view class="right">
					<input v-model="form.voiceId" placeholder="姓的拼音" style="border-bottom: 1px solid rgb(224, 212, 206);"/>
				</view>
			</view>
			<view class="item">
				<view class="left">
					声音的名字:
				</view>
				<view class="right">
					<input v-model="form.voiceName" placeholder="中文名" style="border-bottom: 1px solid rgb(224, 212, 206);"/>
				</view>
			</view>
			<view class="item">
				<view class="left">
					声音的描述:
				</view>
				<view class="right">
					<input v-model="form.voiceDesc" placeholder="例:高冷" style="border-bottom: 1px solid rgb(224, 212, 206);"/>
				</view>
			</view>
			<view class="item">
				<view class="left">
					性别:
				</view>
				<view class="right">
					<radio-group @change="handleSex">
							<label class="radio">
								<radio value="male" :checked="form.gender === 'male'"/>男性
							</label>			
							<label class="radio">
								<radio value="female" :checked="form.gender === 'female'" />女性
							</label>
					</radio-group>
				</view>
			</view>
			<view class="item">
				<view class="left">
					场景:
				</view>
				<view class="right">
					<radio-group @change="handleScenario" style="display: flex;">
							<label class="radio">
								<radio value="story" :checked="form.scenario === 'story'"/>故事
							</label>			
							<label class="radio">
								<radio value="interaction" :checked="form.scenario === 'interaction'" />交互
							</label>
							<label class="radio">
								<radio value="navigation" :checked="form.scenario === 'navigation'" />导航
							</label>
					</radio-group>
				</view>
			</view>
			<view class="item">
				<view class="btn" @click="subClone">
					创建克隆
				</view>			
			</view>
		</view>
		<!-- active:1 end -->
		
		<!-- active:2 start -->
		<view class="content" v-if="active == 1">
			<view class="item">
				<view class="left">
					选择录音的场景:
				</view>
				<view class="right">
					<radio-group @change="handleNoScenario" style="display: flex;">
							<label class="radio">
								<radio value="story" :checked="scenario === 'story'"/>故事
							</label>			
							<label class="radio">
								<radio value="interaction" :checked="scenario === 'interaction'" />交互
							</label>
							<label class="radio">
								<radio value="navigation" :checked="scenario === 'navigation'" />导航
							</label>
					</radio-group>
				</view>
			</view>
			<view class="text" v-if="textList.length > 0">
				{{index >= textList.length ? '您已经录制完毕':textList[index].text}}
			</view>
			<view class="record" v-if="textList.length > 0">
				<image src="../../static/images/mic-on.png" style="height: 170rpx; width: 150rpx;" mode="" v-if="!status"></image>
				<image src="../../static/images/麦克风,声音,录音,录制声音.png" style="height: 170rpx; width: 150rpx;" mode="" v-else></image>
				<view class="btn" @click="switchRecord">{{status == true ? '结束录音':'录音'}}</view>
			</view>
		</view>
		<!-- active:2 end -->
		
		<!-- active:3 start -->
		<view class="content" v-if="active == 2">
			<view class="text" style="color: red; font-size: 30rpx;">
				恭喜已经完成了所有音频录制，现在可以进行提交克隆任务，此提交后的需要等待大概30分钟
			</view>
			<view class="">
				克隆任务：{{title != '' ? title:'请上传克隆的声音'}}
			</view>
			<view class="record">
				<view class="btn" @click="subRecord">提交克隆任务</view>
			</view>
		</view>
		<!-- active:3 end -->
		
		<!-- active:4 start -->
		<view class="content" v-if="active == 3">
			<view class="">
				<view class="title">
					克隆状态:
				</view>
				<view class="item">
					<view class="left">
						任务状态:
					</view>
					<view class="right">
						{{taskStatus == undefined ? '请查询':taskStatus}}
					</view>
				</view>
				<view class="item">
					<view class="left" style="white-space: nowrap">
						任务编号:
					</view>
					<view class="right" style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">
						{{cloneStatus.jobId == undefined?'未知':cloneStatus.jobId}}
					</view>
				</view>
				<view class="item">
					<view class="left">
						声音编号:
					</view>
					<view class="right">
						{{cloneStatus.voiceId == undefined?'未知':cloneStatus.voiceId}}
					</view>
				</view>
				<view class="item">
					<view class="left">
						声音名称:
					</view>
					<view class="right">
						{{cloneStatus.voiceName == undefined?'未知':cloneStatus.voiceName}}
					</view>
				</view>
				<view class="item">
					<view class="left">
						声音性别:
					</view>
					<view class="right">
						{{cloneStatus.gender == undefined?'未知':cloneStatus.gender == 'male' ? '男':'女'}}
					</view>
				</view>
			</view>
			<view class="record">
				<view class="btn" @click="searchClone" style="background-color: orange;">查询克隆任务</view>
			</view>
		</view>
		<!-- active:4 end -->
	</view>
</template>

<script>
	import Http from '../../utils/http';
	const http =new Http()
	const app = getApp()
	export default {
		data() {
			return {
				active: 0,
				list1: [{
					title: '创建克隆任务'
				}, {
					title: '录音'
				}, {
					title: '提交克隆任务'
				}, {
					title: '查询克隆任务'
				}],
				title:'',
				scenario:'',
				textList:[],
				status:false,
				index:0,
				cloneStatus:{},
				shopId:'',
				form:{
					gender:"",
					scenario:"",
					voiceId:'',
					voiceName:'',
					voiceDesc:'',
					recordUrl:'',
					audioRecordId:0,
					jobId:''
				}
			}
		},
		onLoad() {
			this.shopId = app.globalData.shopId;
		},
		computed:{
			taskStatus(){
				let a = '请上传';
				switch(this.cloneStatus.status){
					case 'Initialization':
						a = '初始化中';
						break;
					case 'AudioDetecting':
						a = '音频检查中';
						break;
					case 'PreTraining':
						a = '提交训练，待训练';
						break;
					case 'Training':
						a = '训练中';
						break;
					case 'Success':
						a  = '训练成功';
						break;
					case 'Fail':
						a = '训练失败';
						break;
					default:
						a = '请上传';
						break;
				}
				return a;
			}
		},
		methods: {
			//查询克隆任务
			searchClone(){
				http.get('v1/clone/task/'+this.form.jobId).then(res=>{
					this.cloneStatus = res.data.data.body.data.customizedVoiceJob;
					console.log(this.cloneStatus);
					if(this.cloneStatus.status == 'Success'){
						uni.showToast({
							title:'克隆成功',
							icon:'success'
						})
						let obj = {
							shopId:this.shopId,
							voiceName:this.cloneStatus.voiceId
						}
						http.post('v1/myvoice',obj).then(res=>{
							console.log(res);
						})
					}
				})
			},
			//提交克隆任务
			subRecord(){
				if(this.form.voiceId){
					http.get('v1/clone/sub/'+this.form.voiceId).then(res=>{
						if(res.data.code == 200){
							uni.showToast({
								title:"提交成功",
								icon:'success'
							})
							this.title = res.data.data.voiceId;
							this.active += 1;
						}else{
							
						}
					})
				}else{
					uni.showToast({
						title:'请进行克隆任务',
						icon:'error'
					})
				}
			},
			
			//录音开关
			switchRecord(){
				this.status = !this.status;
				if(this.status){
					this.startRecording();
				}else{
					this.stopRecording();
				}
			},
			//开始录音
			startRecording() {
			    const options = {
			        duration: 60000,
			        sampleRate: 48000,
			        numberOfChannels: 1,
			        format: 'wav',
			        encodeBitRate: 64000, // 设置为 128kbps
			    };
			
			    const recorderManager = wx.getRecorderManager();
			    recorderManager.start(options);
			},
			//结束录音
			stopRecording(){
			    const recorderManager = wx.getRecorderManager();
				const self = this;
			    recorderManager.onStop((res) => {
			        const tempFilePath = res.tempFilePath;
			        // 将录音文件保存为 WAV 格式
			        const fileManager = wx.getFileSystemManager();
			        const wavFilePath = `${wx.env.USER_DATA_PATH}/recording.wav`;
			        fileManager.copyFile({
			            srcPath: tempFilePath,
			            destPath: wavFilePath,
			            success: (res) => {
			                console.log('录音文件已保存为 WAV 格式：', wavFilePath);
							http.upload(wavFilePath).then(res=>{
								// console.log(res);
								let url = JSON.parse(res.data).result.name;
								console.log(`https://jz-cnsiot.oss-cn-shanghai.aliyuncs.com/${url}`);
								self.form.recordUrl = `https://jz-cnsiot.oss-cn-shanghai.aliyuncs.com/${url}`;
								self.form.audioRecordId = self.index + 1;
								http.post('v1/clone/AudioInfo',self.form).then(res=>{
									console.log('`````````````````-----------------------------');
									console.log(res);
									if(res.data.data.body.data.pass == false){
										uni.showToast({
											title:res.data.data.body.data.reason,
											icon:'error'
										})
									}else{
										uni.showToast({
											title:'上传成功，请继续',
											icon:'error'
										})
										self.index = self.index + 1;
										if(self.index >= 20){
											uni.showToast({
												title:'恭喜您录制完毕，请完成提交并耐心等待30分钟',
												icon:'none'
											})
											this.active += 1;
										}
									}
								})
							})
			            },
			            fail:(err)=> {
			                console.error('保存为 WAV 格式失败：', err);
			            }
			        });
			    });
			    recorderManager.stop(); // 停止录音
			},
			//提交克隆
			subClone(){
				console.log(this.form);
				http.post('v1/clone',this.form).then(res=>{
					if(res.data.code == 200){
						this.form.jobId = res.data.data.body.data.jobId;
						uni.showToast({
							title:'任务创建成功，快进行下一步吧'
						})
						if (this.active < this.list1.length - 1) {
							console.log('进入~~~~~~~~~~~~~~~~~~~~');
							this.active += 1;
							console.log(this.active);
						} 
					}else{
						uni.showToast({
							title:'任务创建失败,请检查输入的内容或者更换自定义的声音ID'
						})
					}
				})

			},
			handleNoScenario(e){
				this.scenario = e.detail.value;
				uni.showToast({
					title:'请稍等!',
					icon:'loading'
				})
				///v1/clone/story
				http.get('v1/clone/'+this.scenario).then(res=>{
					if(res.data.code == 200){
						this.textList = res.data.data.body.data.demonstrationList;
					}else{
						uni.showToast({
							title:'网络跑路了，请再次尝试',
							icon:'error'
						})
					}
				})
			},
			handleScenario(e){
				this.form.scenario = e.detail.value;
			},
			handleSex(e){
				this.form.gender = e.detail.value;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container{
		background-color: rgb(238, 234, 249);
		padding: 20rpx;
		height: 100%;
		min-height: 100vh;
		.top{
			box-sizing: border-box;
			height: 100rpx;
			font-size: 80rpx;
			line-height: 100rpx;
			color: orange;
			text-align: center;
		}
		.content{
			margin-top: 30rpx;
			.title{
				height: 50rpx;
				line-height: 50rpx;
				text-align: center;
				font-size: 50rpx;
				color: black;
			}
			margin-top: 20rpx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			.text{
				height: 200rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 30rpx;
				font-weight: bold;
				background-color: white;
				border-radius: 10rpx;
			}
			.record{
				margin-top: 60rpx;
				height: 300rpx;
				background-color: white;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				.btn{
					margin-top: 20rpx;
					width: 200rpx;
					height: 80rpx;
					line-height: 80rpx;
					background-color: red;
					border-radius: 10rpx;
					text-align: center;
				}
			}
			.item {
				height: 80rpx;
				align-items: center;
				font-size: 35rpx;
				display: flex;
				justify-content: center;
				background-color: white;
				margin: 25rpx 0rpx;
				border-radius: 15rpx;
				.left {
					font-weight: bold;
				}
			
				.right {
					margin-left: 20rpx;
					.radio{
						margin: 0 10rpx;
					}
				}
				.btn{
					background-color: orange;
					height: 100%;
					width: 100%;
					border-radius: 10rpx;
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}
		}
	}
</style>
